var mongoose = require("mongoose");

var MongoDB = require("./MongoDB");
var Schemas = require("./Schemas");

var logger = new require("../log/Logger")("AppInfoDao");

var AppInfoModel = MongoDB.getMongoose().model('AppInfoModel', Schemas.AppInfoSchema);
var AppInfoDao = {
    getAppInfo: function(appId) {
        return new Promise(function(reslove, reject) {
            AppInfoModel.findOne({
                appId: appId
            }, function(err, appInfo) {
                logger.info("getAppInfo", appInfo);
                if (!err) {
                    reslove(appInfo);
                } else {
                    logger.error(err);
                    reject();
                }
            });
        });
    },
    getAppInfoList: function() {
        return new Promise(function(reslove, reject) {
            AppInfoModel.find(function(err, appInfoList) {
                if (!err) {
                    reslove(appInfoList);
                } else {
                    reject();
                }
            });
        });
    },
    insertAppInfo : function(appInfo){
        var inserAppInfo = new AppInfoModel(appInfo);

        return new Promise(function(reslove, reject) {
            inserAppInfo.save(function(err){
                if(!err){
                    reslove();
                }else{
                    reject();
                }
            });
        });
    },
    saveAppInfo : function(appInfo) {
        return new Promise(function(reslove, reject) {
            var conditions = {
                appId : appInfo.appId
            };

            var update = {
                $setOnInsert: {
                    appName: appInfo.appName,
                },
                $set: {
                    appName: appInfo.appName,
                    appKey: appInfo.appKey,
                    logSchemaName: appInfo.logSchemaName
                }
            };

            var options = {
                upsert: true
            };

            AppInfoModel.update(conditions, update, options, function(err) {
                if (!err) {
                    reslove();
                } else {
                    reject();
                }
            });
        });
    }
}

module.exports = AppInfoDao;
